<template>
  <div>
    <el-form ref="deptForm" label-width="120px">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartmentById, updateDepartmentById } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }

  },
  data() {
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: []
    }
  },
  created() {
    this.loadEmployee()
    this.loadDepartmentDetail()
  },
  methods: {
    async loadDepartmentDetail() {
      if (!this.isEdit) return
      const res = await getDepartmentById(this.id)
      this.form = res.data
    },

    async loadEmployee() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res.data
    },
    hCancel() {},
    async hSubmit() {
      try {
        // 1. 兜底校验
        // 2. 发请求 (API 的封装)
        // 根据当前的状态来决定做添加操作还是编辑操作
        let res = null
        if (this.isEdit) {
          res = await updateDepartmentById(this.form)
        } else {
          this.form.pid = this.id
          res = await addDepartments(this.form)
        }
        // 3. 根据状态提醒用户
        this.$message.success(res.message)
        // 4. 关闭 dialog
        // 5. 再次发请求获取最新的部门信息
        // 子传父: 触发父组件绑定的事件 success
        this.$emit('success')
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }

}
</script>

<style>

</style>
